<?php
/**接收客户端提交的uname和pid 实现购物车条目的操作 **/
header('Content-Type:application/json;CHARSET=UTF-8');
@$uname=$_REQUEST['uname'] or die('{"msg":"err","reason":"uname required"}');
@$upwd=$_REQUEST['upwd'] or die('{"msg":"err","reason":"upwd required"}');

require("0_init.php");

$sql="SELECT uid FROM jd_user WHERE uname='$uname'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_row($result);
if($row){//能够根据用户名查到用户id
	$uid=$row[0];
}else{
	die('{"msg":"err","reason":"unmae non-exists"}');
}
//根据用户编号查找购物车编号
$sql="SELECT cid FROM jd_cart WHERE userId='$uid'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_row($result);
if($row){
	$cid=$row[0];//查询到当前用户的购物车编号
}else{//当前用户没有对应的购物车编号 则执行添加语句生成购物车 得到购物车编号
	$sql="INSERT INTO jd_cart VALUES(NULL,'$uid')";
	mysqli_query($conn,$sql);
	$cid=mysqli_insert_id($conn);//获得刚刚生成的自增编号
}
//根据购物车编号和产品编号 到详情表查询是否有该记录
$sql="SELECT did,count FROM jd_cart_detail WHERE cartId='$cid' AND productId='$pid'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_row($result);
if(!$row){//当前购物车尚未购买过商品
	$count=1;
	$sql="INSERT INTO jd_cart_detail VALUES(NULL,'$cid','$pid','$count')";
	mysqli_query($conn,$sql);
}else{//当前购物车已经购买过商品
	$did=$row[0];//详情编号
	$count=$row[1];//已购买的数量
	$count++;
	$sql="UPDATE jd_cart_detail SET count=$count WHERE did='$did'";
	mysqli_query($conn,$sql);
}
echo '{"msg":"succ","count":'.$count.'}';

